Completed
Push — master ( a05f1c...07f85d )
by greg
03:17
created

file.js ➔ getAllWithKeys   B

Complexity

Conditions 1
Paths 64

Size

Total Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
nc 64
dl 0
loc 42
rs 8.8571
nop 1

1 Function

Rating   Name   Duplication   Size   Complexity  
F file.js ➔ ... ➔ files.forEach 0 32 11
1
import path from 'path'
2
import mkdirp from 'mkdirp'
3
import fse from 'fs-extra'
4
import moment from 'moment'
5
6
import {
7
  abeExtend,
8
  coreUtils,
9
  cmsData,
10
  config
11
} from '../../'
12
13
export function getAllWithKeys(withKeys) {
14
  var files = cmsData.file.getFiles(path.join(config.root, config.data.url), true, 99, /\.json/)
15
  var filesArr = []
16
17
  files.forEach(function (file) {
18
    var cleanFile = file
19
    var json = cmsData.file.get(file.path)
20
21
    if(json.abe_meta.latest.date != null) {
22
      file.date = json.abe_meta.latest.date
23
      file.cleanDate = moment(json.abe_meta.latest.date).format('YYYY/MM/DD HH:MM:ss')
24
    }
25
26
    if(json.abe_meta != null) {
27
      var date = null
28
      if (json.abe_meta.latest.date !== null) {
29
        date = json.abe_meta.latest.date
30
      } else if (json.abe_meta.date !== null) {
31
        date = json.abe_meta.date
32
      }
33
      cleanFile.abe_meta = {
34
        date: date,
35
        type: (json.abe_meta.type != null) ? json.abe_meta.type : null,
36
        link: (json.abe_meta.link != null) ? json.abe_meta.link : null,
37
        template: (json.abe_meta.template != null) ? json.abe_meta.template : null,
38
        status: (json.abe_meta.status != null) ? json.abe_meta.status : null,
39
        cleanName: (json.abe_meta.cleanName != null) ? json.abe_meta.cleanName : null,
40
        cleanFilename: (json.abe_meta.cleanFilename != null) ? json.abe_meta.cleanFilename : null
41
      }
42
    }
43
    Array.prototype.forEach.call(withKeys, (key) => {
44
      var keyFirst = key.split('.')[0]
45
      cleanFile[keyFirst] = json[keyFirst]
46
    })
47
    filesArr.push(cleanFile)
48
  })
49
50
  var merged = cmsData.revision.getFilesMerged(filesArr)
51
52
  abeExtend.hooks.instance.trigger('afterGetAllFiles', merged)
53
  return merged
54
}
55
56
export function get(pathJson) {
57
  var json = {}
58
  pathJson = abeExtend.hooks.instance.trigger('beforeGetJson', pathJson)
59
  
60
  try {
61
    var stat = fse.statSync(pathJson)
62
    if (stat) {
63
      json = fse.readJsonSync(pathJson)
64
    }
65
  }catch(e) {
0 ignored issues
show
Coding Style Comprehensibility Best Practice introduced by
Empty catch clauses should be used with caution; consider adding a comment why this is needed.
Loading history...
66
  }
67
68
  json = abeExtend.hooks.instance.trigger('afterGetJson', json)
69
  return json
70
}
71
72
export function fromUrl(url) {
73
  var res = {
74
    root: '',
75
    draft: {
76
      dir: '',
77
      file: '',
78
      path: ''
79
    },
80
    publish: {
81
      dir: '',
82
      file: '',
83
      link: '',
84
      path: '',
85
      json: ''
86
    },
87
    json: {
88
      path: '',
89
      file: ''
90
    }
91
  }
92
93
  if(url != null) {
94
95
    var dir = path.dirname(url).replace(config.root, '')
96
    var filename = path.basename(url)
97
    var link = url.replace(config.root, '')
98
    link = link.replace(/^\//, '').split('/')
99
    link.shift()
100
    link = cmsData.fileAttr.delete('/' + link.join('/').replace(/\/$/, ''))
101
102
    let draft = config.draft.url
103
    let publish = config.publish.url
104
    let data = config.data.url
105
106
    res.root = config.root
107
108
    // set dir path draft/json
109
    res.draft.dir = coreUtils.file.changePath(dir, draft)
110
    res.json.dir = coreUtils.file.changePath(dir, data)
111
    res.publish.dir = coreUtils.file.changePath(dir, publish)
112
    res.publish.json = res.json.dir
113
114
    // set filename draft/json
115
    res.draft.file = filename
116
    res.publish.file = cmsData.fileAttr.delete(filename)
117
    res.publish.link = link
118
    res.json.file = filename.replace(`.${config.files.templates.extension}`, '.json')
119
    res.publish.json = path.join(res.json.dir, cmsData.fileAttr.delete(res.json.file))
120
121
    // set filename draft/json
122
    res.draft.path = path.join(res.draft.dir, res.draft.file)
123
    res.publish.path = path.join(res.publish.dir, res.publish.file)
124
    res.json.path = path.join(res.json.dir, res.json.file)
125
  }
126
  return res
127
}
128
129
export function getFolders(folder, flatten = false, level) {
130
  var arr = []
0 ignored issues
show
Unused Code introduced by
The assignment to variable arr seems to be never used. Consider removing it.
Loading history...
131
  arr = cmsData.file.read(
132
    folder.replace(/\/$/, ''), 
133
    folder.replace(/\/$/, ''), 
134
    'folders', 
135
    flatten, 
136
    /(.*?)/, 
137
    level
138
  )
139
140
  return arr
141
}
142
143
export function getFiles(folder, flatten = false, level, extensions = /(.*?)/, inversePattern = false) {
144
145
  var arr = []
0 ignored issues
show
Unused Code introduced by
The assignment to variable arr seems to be never used. Consider removing it.
Loading history...
146
  arr = cmsData.file.read(
147
    folder.replace(/\/$/, ''),
148
    folder.replace(/\/$/, ''), 
149
    'files', 
150
    flatten, 
151
    extensions, 
152
    level, 
153
    0, 
154
    inversePattern
155
  )
156
157
  return arr
158
}
159
160
export function getFilesByType(pathFile, type = null) {
161
  try {
162
    var directory = fse.lstatSync(pathFile)
163
    if (!directory.isDirectory()) {
164
      mkdirp.sync(pathFile)
165
    }
166
  } catch (e) {
167
    mkdirp.sync(pathFile)
168
  }
169
  var files = cmsData.file.getFiles(pathFile, true, 20, new RegExp(`.${config.files.templates.extension}`))
170
171
  var result = []
172
173
  Array.prototype.forEach.call(files, (file) => {
174
    var val = cmsData.fileAttr.get(file.path).s
175
    if(type === null || val === type) result.push(file)
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
176
  })
177
  return result
178
}
179
180
export function getFileObject(elt, pathLevel, base) {
181
  var cleanName = cmsData.fileAttr.delete(elt)
182
  var cleanNameNoExt = cleanName.replace(/\..+$/, '')
183
  var fileData = cmsData.fileAttr.get(elt)
184
185
  var date
186
  if (fileData.d) {
187
    date = fileData.d
188
  }else {
189
    var stat = fse.statSync(pathLevel)
190
    date = stat.mtime
191
  }
192
  var cleanFilePath = cmsData.fileAttr.delete(pathLevel).replace(config.root, '').replace(/^\/?.+?\//, '')
193
194
  var fileDate = moment(date)
195
  var duration = moment.duration(moment(fileDate).diff(new Date())).humanize(true)
196
197
  var filePath = pathLevel.replace(config.root, '')
198
  filePath = filePath.split('/')
199
  filePath.shift()
200
  filePath = filePath.join('/')
201
  var item = {
202
    'name': elt,
203
    'path': pathLevel,
204
    'cleanPathName': cmsData.fileAttr.delete(pathLevel),
205
    'cleanPath': pathLevel.replace(base + '/', ''),
206
    'date': date,
207
    'cleanDate': fileDate.format('YYYY/MM/DD HH:MM:ss'),
208
    'duration': duration,
209
    'cleanName': cleanName,
210
    'cleanNameNoExt': cleanNameNoExt,
211
    'cleanFilePath': cleanFilePath,
212
    'filePath': filePath,
213
    'type': 'file'
214
  }
215
216
  return item
217
}
218
219
export function read(base, dirName, type, flatten, extensions = /(.*?)/, max = 99, current = 0, inversePattern = false) {
220
  var arr = []
221
  var level = fse.readdirSync(dirName)
222
  var fileCurrentLevel = []
223
  let assets = config.files.templates.assets
224
225
  for (var i = 0; i < level.length; i++) {
226
    var pathLevel = dirName + '/' + level[i]
227
    var isFolder = true
228
    try {
229
      var directory = fse.lstatSync(pathLevel)
230
      if (!directory.isDirectory()) {
231
        isFolder = false
232
      }
233
    } catch (e) {
234
      isFolder = false
235
    }
236
    var match = (isFolder) ? true : (inversePattern) ? !extensions.test(level[i]) : extensions.test(level[i])
237
    if((type === 'files' || type === null) && match) {
238
239
      if(level[i].indexOf('.') > -1) {
240
        var item = cmsData.file.getFileObject(level[i], pathLevel, item)
0 ignored issues
show
Bug introduced by
The variable item seems to not be initialized for all possible execution paths. Are you sure getFileObject handles undefined variables?
Loading history...
241
        if(!flatten) item['folders'] = []
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
242
        arr.push(item)
243
        // push current file name into array to check if siblings folder are assets folder
244
        fileCurrentLevel.push(level[i].replace(/\..+$/, '') + assets)
245
      }
246
    }
247
    if(!fileCurrentLevel.indexOf(level[i]) >= 0 && match) {
248
      if(isFolder) {
249
        if(!flatten) {
250
          var index = arr.push(
251
            {
252
              'name': level[i],
253
              'path': pathLevel,
254
              'cleanPath': pathLevel.replace(base + '/', ''),
255
              'folders': [],
256
              'type': 'folder'
257
            }
258
          ) - 1
259
          if(current < max){
260
            arr[index].folders = cmsData.file.read(base, pathLevel, type, flatten, extensions, max, current + 1, inversePattern)
261
          }
262
        }else {
263
          if(type === 'folders' || type === null) {
264
            arr.push(
265
              {
266
                'name': level[i],
267
                'path': pathLevel,
268
                'cleanPath': pathLevel.replace(base + '/', ''),
269
                'type': 'folder'
270
              }
271
            )
272
          }
273
          if(current < max){
274
            Array.prototype.forEach.call(cmsData.file.read(base, pathLevel, type, flatten, extensions, max, current + 1, inversePattern), (files) => {
275
              arr.push(files)
276
            })
277
          }
278
        }
279
      }
280
    }
281
  }
282
283
  return arr
284
}